<template>
  <BasicDrawer
    :destroyOnClose="true"
    v-bind="$attrs"
    @register="registerDrawer"
    :showFooter="true"
    width="680px"
    @ok="onSave"
    okText="退卡"
    :maskClosable="false"
  >
    <a-flex justify="center">
      <card-head :item="cardItem" />
    </a-flex>

    <div
      style="
        font-weight: 500;
        font-size: 16px;
        color: #333333;
        padding: 8px 0;
        margin-bottom: 4px;
        margin-top: 12px;
      "
    >
      购买信息
    </div>

    <div
      style="
        background: #ffffff;
        box-shadow: 0 1px 6px 0 rgba(229, 197, 197, 0.5);
        border-radius: 4px;
        padding: 12px;
      "
    >
      <a-flex
        align="center"
        justify="space-between"
        style="
          background: #f9f9f9;
          box-shadow: inset 0 -1px 0 0 #fff0f0;
          border-radius: 4px 4px 0 0;
          height: 56px;
          margin: -12px -12px 12px -12px;
          padding: 0 12px;
        "
      >
        <span style="font-weight: 600; font-size: 18px; color: #c95e78">{{
          cardItem.cardName
        }}</span>
        <span
          style="font-weight: 600; font-size: 18px; color: #c95e78"
          v-html="getCardOriginalDesc(cardItem)"
        ></span>
      </a-flex>

      <a-flex>
        <div style="flex: 1">
          <div style="font-size: 14px; color: #6d414c">卡项</div>
          <div style="font-size: 14px; color: #6d414c; margin-top: 8px"
            >{{ record.cardConsumeName || record.goodsName || '--' }}
          </div>

          <div
            v-if="quoteCardItem.cardType === 100"
            style="font-weight: 400; font-size: 14px; color: #666666"
          >
            <span> {{ getProductDiscount(quoteCardItem) }}</span>
            <span>余额</span> <span>¥</span
            ><span>{{
              (quoteCardItem.remainAmount || 0) + (quoteCardItem.remainBounsScore || 0)
            }}</span>
          </div>
        </div>

        <div style="flex: 1">
          <div style="font-size: 14px; color: #6d414c">美容师</div>
          <div style="font-size: 14px; color: #6d414c; margin-top: 8px"
            >{{ record.cashierName }}
          </div>
        </div>

        <div style="flex: 1; text-align: right">
          <div
            style="font-weight: 400; font-size: 14px; color: #999999; text-decoration: line-through"
          >
            <span>零售价</span><span>{{ cardItem.salePrice }}</span>
          </div>

          <div style="margin-top: 6px"
            ><span style="font-size: 14px; color: #6d414c">折后价&nbsp;&nbsp;¥</span
            ><span style="font-size: 20px; color: #6d414c">
              {{ record.transactionPrice }}</span
            ></div
          >
        </div>
      </a-flex>

      <div style="border-bottom: 1px solid #d8d8d8; width: 100%; margin: 12px 0" />

      <div style="text-align: right">
        <div
          ><span style="font-size: 14px; color: #6d414c">应付&nbsp;&nbsp;¥</span>
          <!--          <span style="font-weight: 500;font-size: 20px;color: #6D414C;"> {{
              record.totalTransactionPrice
            }}
          </span>-->
          <!--          <span style="font-weight: 500;font-size: 20px;color: #6D414C;"> {{
              cardItem.returnMoneyCardPrice || cardItem.remainAmount || 0
            }}
          </span>-->
          <span style="font-weight: 500; font-size: 20px; color: #6d414c">
            {{ round(record.shareCashPirce / (record.goodsQty || 1) || 0) }}
          </span>
        </div>
      </div>
    </div>

    <div
      style="font-weight: 500; font-size: 16px; color: #333333; padding: 8px 0; margin-top: 12px"
    >
      退款信息
    </div>

    <BasicForm @register="registerForm1">
      <template #payExtensionCode="{ model, field }">
        <div class="data-group">
          <div
            :class="['use', 'cell', model[field] === o.value ? 'active' : 'tacit']"
            v-for="o in currentCashPayCodes"
            :key="o.value"
            @click="model[field] = o.value"
            >{{ o.label }}
          </div>
        </div>
      </template>

      <template #totalReturnPrice="{ model, field }">
        <a-row :gutter="24" align="middle">
          <a-col :span="24">
            <!--            cardItem.returnMoneyCardPrice || 0-->
            <a-input-number v-model:value="model[field]" :min="0" :max="9999999" :precision="2" />
          </a-col>
        </a-row>
      </template>
    </BasicForm>
    <BackDetail @register="registerDetail1" />
  </BasicDrawer>
</template>

<script setup>
  import { computed, defineOptions, nextTick, reactive, ref } from 'vue';

  import { BasicDrawer, useDrawerInner, useDrawer } from '@/components/Drawer';

  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicForm, useForm } from '@/components/Form';
  import { cashPayCodes, refundList2 } from '@/api/ds.js';
  import { POST } from '@/api/http.js';
  import { getUserInfo } from '@/utils/auth';
  import { round } from '@/api/util.js';
  import { getCardOriginalDesc, getProductDiscount } from '@/views/member/util.js';

  import CardHead from '../member/card-head.vue';

  import BackDetail from '../member/back-detail.vue';

  const [registerDetail1, { openDrawer: TDlDrawer }] = useDrawer();

  defineOptions({ name: 'OrderRefund2' });

  const emit = defineEmits(['complete']);
  const state = reactive({ title: '' });

  const orderHeader = ref([]);
  // cashier/getMasterOrderDetailsBean 字段 responseMasterOrderItemBeanList
  const record = ref({});

  // 购买的卡 card/getUserOneCardBenefitsInfo
  const cardItem = ref({});
  // 抵扣卡 card/getUserOneCardBenefitsInfo
  const quoteCardItem = ref({});

  const { createMessage } = useMessage();

  const currentCashPayCodes = computed(() => {
    return cashPayCodes;
  });

  const [registerForm1, form1] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24, style: { paddingRight: '36px' } },

    schemas: [
      {
        label: '退款类型',
        field: 'refundChannels',
        required: true,
        component: 'RadioGroup',
        componentProps: {
          options: refundList2,
          onChange(e) {
            if (e.target.value === '1') {
              form1.setFieldsValue({
                payExtensionCode: null,
              });

              form1.updateSchema({
                field: 'payExtensionCode',
                ifShow: false,
              });
            } else {
              form1.updateSchema({
                field: 'payExtensionCode',
                ifShow: true,
              });
            }
          },
        },
      },

      {
        label: '退款金额',
        field: 'totalReturnPrice',
        required: true,
        component: 'InputNumber',
        componentProps: {
          min: 0,
          precision: 2,
        },
        slot: 'totalReturnPrice',
      },

      {
        label: '退款方式',
        field: 'payExtensionCode',
        required: true,
        component: 'RadioGroup',
        slot: 'payExtensionCode',
      },

      {
        label: '退款原因',
        field: 'cancelCustom',
        required: true,
        component: 'InputTextArea',
        componentProps: {
          rows: 6,
          maxlength: 200,
          showCount: true,
        },
      },
    ],
    showActionButtonGroup: false,
  });

  const [registerDrawer, { closeDrawer }] = useDrawerInner(
    async ({
      orderHeader: header,
      record: item,
      /**
       * 接口 getUserCardListNoInfo
       * 字段 cardTimesPack, cardMoneyPack
       */
      cardItem: baseCI,
    }) => {
      orderHeader.value = header;
      record.value = item;

      await form1.resetFields();

      console.log(baseCI, 'baseCI');

      // await form1.setFieldsValue({totalReturnPrice: baseCI.returnMoneyCardPrice || 0 || record.value.totalTransactionPrice || 0})

      const { memberCode } = orderHeader.value;
      const { cardConsumeCode } = record.value;
      const { cardNo } = baseCI;

      form1.updateSchema([
        {
          field: 'refundChannels',
          show: !!cardConsumeCode,
        },
      ]);

      cardItem.value =
        (
          await POST('/card/getUserOneCardBenefitsInfo', {
            pageFlag: false,
            memberCode,
            cardNo,
          })
        )?.userCardPack ?? {};

      form1.updateSchema([
        {
          field: 'refundChannels',
          componentProps: {
            options:
              cardItem.value.upgradeFlag === 1
                ? refundList2.filter((d) => d.value === '2')
                : refundList2,
          },
        },
      ]);

      /**
       * 退款金额字段
       * 次数卡应退金额   remainAmount
       * 金额卡应退金额  returnMoneyCardPrice
       */
      await form1.setFieldsValue({
        totalReturnPrice:
          cardItem.value.cardSubType === '101'
            ? cardItem.value.returnMoneyCardPrice
            : cardItem.value.remainAmount,
      });

      if (!!cardConsumeCode) {
        quoteCardItem.value =
          (
            await POST('/card/getUserOneCardBenefitsInfo', {
              pageFlag: false,
              memberCode,
              cardNo: cardConsumeCode,
            })
          )?.userCardPack ?? {};
      }
    },
  );

  async function onSave() {
    const formData = form1.getFieldsValue();
    const { cancelCustom, payExtensionCode, returnGoodsQty, totalReturnPrice, refundChannels } =
      formData;

    console.log(record.value, 'record.value');

    const { itemGoodsType, extensionCode, goodsQty, extensionId, storeCode, benefitsType } =
      record.value;

    const { employeeCode: cashierCode, realName: cashierName } =
      (await getUserInfo())?.resultBean ?? {};

    const { cardNo: goodsSn, cardName: goodsName } = cardItem.value;
    // const returnPrice = round(totalReturnPrice / goodsQty * returnGoodsQty);

    const item = {
      payExtensionCode,
      itemGoodsType,
      extensionCode,
      goodsQty: 1,
      returnGoodsQty: 1,
      returnPrice: totalReturnPrice,
      totalReturnPrice,
      isBack: 1,
      goodsSn,
      goodsName,
      extensionId,
      storeCode,
      benefitsType,
      refundChannels,
      cashierCode,
      cashierName,
    };

    const { masterOrderSn, memberCode } = orderHeader.value;
    const data = {
      masterOrderSn,
      memberCode,
      cashierCode,
      cashierName,
      cancelCustom,
      source: '21',
      referer: 'PC端',
      orderItemBeanList: [item],
    };

    const res = await POST('/cashier/createTDShopCardOrders', data);
    createMessage.success('退卡成功');
    emit('complete')
    TDlDrawer(true, { record: res });
    // closeDrawer();
  }
</script>

<style lang="less" scoped>
  .card {
    margin: 8px 0 46px;
    padding: 12px;

    .c-title {
      display: flex;
      flex-direction: row;
      align-items: center;
      column-gap: 8px;
      color: #091f3d;
      font-size: 15px;
      font-weight: 600;
    }

    .c-body {
      margin-top: 16px;

      .label {
        color: #acb4bf;
      }

      .value {
        color: #091f3d;
      }
    }
  }
</style>

<style lang="less" scoped>
  .data-group {
    display: flex;
    flex-flow: row wrap;
    align-items: center;
    cursor: pointer;
    gap: 8px 12px;

    .cell {
      padding: 4px 20px;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 400;
    }

    .tacit {
      border: 1px solid #e0e5ec;
      color: #091f3d;
    }

    .active {
      border: 1px solid @primary-color;
      background-color: @primary-color;
      color: #fff;
    }
  }
</style>
